import { useCookies } from '@vueuse/integrations/useCookies'
import { login, menu, user } from '@/api/auth'

const TOKEN = 'auth_token'
const cookies = useCookies(['locale'])

const auth = {
  state: {
    user: {},
    token: cookies.get(TOKEN) || '',
    menus: []
  },
  mutations: {
    setToken(state, token) {
      cookies.set(TOKEN, token)
      state.token = token
    },
    setUser(state, info) {
      state.user = info
    },
    setMenus(state, menus) {
      state.menus = menus
    }
  },
  getters: {
    token: (state) => state.token,
    user: (state) => state.user,
    menus: (state) => state.menus
  },
  actions: {
    login({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        login({ username, password })
          .then(({ code, data }) => {
            console.log(code, data)
            if (code === 200) {
              commit('setToken', data.token)
              resolve(data.token)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    getUser({ commit }) {
      return new Promise((resolve, reject) => {
        user()
          .then(({ code, data }) => {
            if (code === 200) {
              commit('setUser', data)
              resolve(data)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    getMenus({ commit }) {
      return new Promise((resolve, reject) => {
        menu()
          .then(({ code, data }) => {
            if (code === 200) {
              console.log(data)
              commit('setMenus', data)
              resolve(data)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
  }
}

export default auth
